package com.quanyan.stadium.web.api.v2;

import com.quanyan.api.APIResponse;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.exception.BizException;
import com.quanyan.common.utils.ObjectUtil;
import com.quanyan.stadium.api.req.ReqId;
import com.quanyan.stadium.api.req.gameEventConfig.ReqClubCreateGameEvent;
import com.quanyan.stadium.api.req.v2.ReqClubGameEvent;
import com.quanyan.stadium.api.req.v3.ReqGameRoundV2;
import com.quanyan.stadium.api.resp.v2.RespUserGameTypeAndClub;
import com.quanyan.stadium.biz.BizGameSystemDao;
import com.quanyan.stadium.entity.TbGameEvent;
import com.quanyan.stadium.enums.GameSystemConfigEnum;
import com.quanyan.stadium.enums.errorEnum.CreateCompListErrorEnum;
import com.quanyan.stadium.service.gameEvent.ClubGameEventConfigService;
import com.quanyan.stadium.transfer.GameConfigTransfer;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;

/**
 * 内部赛所有信息
 *
 * */
@RestController("clubGameEvent")
@RequestMapping("/api/stadium/clubGameEvent")
public class ClubGameEventController {

    private final static Logger logger = LoggerFactory.getLogger(ClubGameEventController.class);


    @Autowired
    private ClubGameEventConfigService clubGameEventConfigService;

    @Autowired
    private BizGameSystemDao bizGameSystemDao;

    @Autowired
    private GameConfigTransfer gameEventTransfer;

    /**
     * 内部赛----创建.涉及到赛事的创建
     *
     * */
    @RequestMapping(value="/createClubGameEvent", method = RequestMethod.POST)
    public APIResponse<?> createClubGameEvent(@RequestBody @Valid ReqClubCreateGameEvent reqClubCreateGameEvent, BindingResult result, HttpServletRequest request) throws Exception {
        if(result.hasErrors()) {
            return APIResponse.returnFail(result.getFieldError().getDefaultMessage());
        }
        return APIResponse.returnSuccess(clubGameEventConfigService.createGameEvent(reqClubCreateGameEvent, (Integer) request.getAttribute("uid")));
    }

    /**
     * 内部赛----排行榜
     *
     * */
    @RequestMapping(value="/clubGameEventRankList", method = RequestMethod.POST)
    public APIResponse<?> clubGameEventRankList(@RequestBody @Valid ReqId reqId, HttpServletRequest request) throws InvocationTargetException, IllegalAccessException {
        if(null == reqId.getGameEventId() || reqId.getGameEventId() < 1) {
            return APIResponse.returnFail("赛事不存在");
        }
        return APIResponse.returnSuccess(clubGameEventConfigService.clubGameEventRankList(reqId.getGameEventId(), (Integer) request.getAttribute("uid")));
    }

    /**
     * 内部赛----赛事编排,生成新的一轮
     *
     * */
    @RequestMapping(value="/openNextGameRound", method = RequestMethod.POST)
    public APIResponse<?> openNextGameRound(@RequestBody @Valid ReqId reqId, HttpServletRequest request) throws Exception {
        if(null == reqId.getGameEventId() || reqId.getGameEventId() < 1) {
            return APIResponse.returnFail("赛事不存在");
        }
        if(null == reqId.getGameRoundId() || reqId.getGameRoundId() < 1) {
            return APIResponse.returnFail("当前轮次不存在");
        }
        return APIResponse.returnSuccess(clubGameEventConfigService.openNextGameRoundV2(reqId.getGameEventId(), reqId.getGameRoundId(), (Integer) request.getAttribute("uid")));
    }

    /**
     * 内部赛----详情
     *
     * */
    @RequestMapping(value="/clubGameEventDetail", method = RequestMethod.POST)
    public APIResponse<?> clubGameEventDetail(@RequestBody @Valid ReqId reqId, HttpServletRequest request) throws InvocationTargetException, IllegalAccessException {
        if(null == reqId.getGameEventId() || reqId.getGameEventId() < 1) {
            return APIResponse.returnFail("赛事不存在");
        }
        return APIResponse.returnSuccess(clubGameEventConfigService.clubGameEventDetailV2(reqId.getGameEventId(), (Integer) request.getAttribute("uid")));
    }

    /**
     * 内部赛----赛事取消
     *
     * */
    @RequestMapping(value="/cancelClubGameEvent", method = RequestMethod.POST)
    public APIResponse<?> cancelClubGameEvent(@RequestBody @Valid ReqId reqId, HttpServletRequest request) throws InvocationTargetException, IllegalAccessException {
        if(null == reqId.getGameEventId() || reqId.getGameEventId() < 1) {
            return APIResponse.returnFail("赛事不存在");
        }
        clubGameEventConfigService.cancelClubGameEvent(reqId.getGameEventId(), (Integer) request.getAttribute("uid"));
        return APIResponse.returnSuccess();
    }


    /**
     * 赛事----获取用户栏目对应的俱乐部信息
     *
     * */
    @RequestMapping(value="/userClubMsgAndGameType", method = RequestMethod.POST)
    public APIResponse<?> userClubMsgAndGameType(HttpServletRequest request) throws InvocationTargetException, IllegalAccessException {
        RespUserGameTypeAndClub result = clubGameEventConfigService.userClubMsgAndGameType((Integer) request.getAttribute("uid"));
        if (null != result && CollectionUtils.isNotEmpty(result.getParamClub().get(0))) {
            return APIResponse.returnFail("服务版本不匹配");
        }
        return APIResponse.returnSuccess(result);
    }

    /**
     * 内部赛查询配置
     * @return
     */
    @RequestMapping(value="/cludGameQueryConfig", method = RequestMethod.POST)
    public  APIResponse<?>  cludGameQueryConfig(HttpServletRequest request) {
        Integer uid = (Integer)request.getAttribute("uid");
        return APIResponse.returnSuccess(clubGameEventConfigService.getClubGameEventConfig(uid));
    }

    /**
     * 赛事----获取用户栏目对应的俱乐部信息
     *
     * */
    @RequestMapping(value="/generateRoundAndSchedule", method = RequestMethod.POST)
    public APIResponse<?> generateRoundAndSchedule(@RequestBody @Valid ReqGameRoundV2 gameRoundV2, HttpServletRequest request) throws Exception {
        if(null == gameRoundV2.getGameEventId() || gameRoundV2.getGameEventId() < 1) {
            return APIResponse.returnFail("赛事不存在");
        }
        TbGameEvent tbGameEvent = bizGameSystemDao.selectTbGameEvent(gameRoundV2.getGameEventId());
        if (tbGameEvent.getSignEndTime().after(new Date())) {
            throw new BizException(null, "报名时间还未截止,比赛不能开始编排");
        }
        int currentNum = tbGameEvent.getTeamLimitNum() - tbGameEvent.getInventoryLevel();
        //校验起始人数
        if (currentNum<3) {
            return APIResponse.returnFail(Integer.parseInt(CreateCompListErrorEnum.CREATE_COMP_LIST_ERROR_12.getCode()), CreateCompListErrorEnum.CREATE_COMP_LIST_ERROR_12.getName());
        }
        //校验赛制人数
        if (tbGameEvent.getGameSystemType().intValue() == GameSystemConfigEnum.CONFIG_GAME_TYPE_EIGHT_RULE.getId()) {
            if (currentNum != 8) {
                return APIResponse.returnFail(Integer.parseInt(CreateCompListErrorEnum.CREATE_COMP_LIST_ERROR_12.getCode()), CreateCompListErrorEnum.CREATE_COMP_LIST_ERROR_12.getName());
            }
        }else if (tbGameEvent.getGameSystemType().intValue() == GameSystemConfigEnum.CONFIG_GAME_TYPE_UNSET_RULE.getId()) {
                if (currentNum >8 || currentNum <5) {
                    return APIResponse.returnFail(Integer.parseInt(CreateCompListErrorEnum.CREATE_COMP_LIST_ERROR_12.getCode()), CreateCompListErrorEnum.CREATE_COMP_LIST_ERROR_12.getName());
                }
        }else if (tbGameEvent.getGameSystemType().intValue() == GameSystemConfigEnum.CONFIG_GAME_TYPE_MIXED.getId()) {
            if (null == gameRoundV2.getGroupNum() || gameRoundV2.getGroupNum() < 2) {
                return APIResponse.returnFail("分组数目不合法");
            }
            if (null == gameRoundV2.getPromotedNum() || gameRoundV2.getPromotedNum() < 1){
                return APIResponse.returnFail("每组晋级人数不合法");
            }
            tbGameEvent.setTeamGroupNum(gameRoundV2.getGroupNum());
            tbGameEvent.setTeamLimitNum(gameRoundV2.getPromotedNum());
            bizGameSystemDao.updateTbGameEvent(tbGameEvent);
        }

        //校验双打人数
        boolean isDouble = false;
        if (gameEventTransfer.getGameCategoryById(tbGameEvent.getGameCategoryType().intValue()).getMinNum() == 2
                && gameEventTransfer.getGameCategoryById(tbGameEvent.getGameCategoryType().intValue()).getMaxNum() == 2) {
            isDouble = true;
            if (currentNum<4 || currentNum%2 != 0){
                return APIResponse.returnFail(Integer.parseInt(CreateCompListErrorEnum.CREATE_COMP_LIST_ERROR_13.getCode()), CreateCompListErrorEnum.CREATE_COMP_LIST_ERROR_13.getName());
            }
        }
        //校验比赛是否开启
        if (tbGameEvent.getCurrentRoundId() > 0) {
            return APIResponse.returnFail("比赛已经开始,无法生成对战信息");
        }
        clubGameEventConfigService.generateRoundAndSchedule(tbGameEvent, isDouble, (Integer) request.getAttribute("uid"), gameRoundV2);
        return APIResponse.returnSuccess();
    }

    /**
     * 内部赛----当前报名用户
     *
     * */
    @RequestMapping(value="/queryRespGameMember", method = RequestMethod.POST)
    public APIResponse<?> queryRespGameMember(@RequestBody @Valid ReqId reqId, HttpServletRequest request) throws Exception {
        if(null == reqId.getGameEventId() || reqId.getGameEventId() < 1) {
            return APIResponse.returnFail("赛事不存在");
        }
        return APIResponse.returnSuccess(clubGameEventConfigService.queryRespGameMember(reqId.getGameEventId(), (Integer)request.getAttribute("uid")));
    }

    @RequestMapping(value="/queryClubGameEventList", method = RequestMethod.POST)
    public  APIResponse<?> queryClubGameEventList(@RequestBody @Valid ReqClubGameEvent reqClubGameEvent, HttpServletRequest request){

        try{
            Integer uid = (Integer)request.getAttribute("uid");
            reqClubGameEvent.setUid(uid);

            return APIResponse.returnSuccess(PageObj.create(0, reqClubGameEvent.getPageNo(), reqClubGameEvent.getPageSize(), clubGameEventConfigService.queryClubGameEventList(reqClubGameEvent)));
        }catch (Exception e) {
            logger.error("queryClubGameEventList exception:", e);
            return APIResponse.returnFail("服务器异常");
        }
    }

    @RequestMapping(value="/queryUidClubGameEventList", method = RequestMethod.POST)
    public  APIResponse<?> queryUidClubGameEventList(@RequestBody @Valid ReqClubGameEvent reqClubGameEvent, HttpServletRequest request){

        try{
            Integer uid = (Integer)request.getAttribute("uid");
            if (ObjectUtil.isObjectEmpty(uid)) {
                return APIResponse.returnFail("uid is not null");
            }
            reqClubGameEvent.setUid(uid);

            return APIResponse.returnSuccess(PageObj.create(0, reqClubGameEvent.getPageNo(), reqClubGameEvent.getPageSize(), clubGameEventConfigService.queryUidClubGameEventList(reqClubGameEvent)));
        }catch (Exception e) {
            logger.error("queryUidClubGameEventList exception:", e);
            return APIResponse.returnFail("服务器繁忙，请稍后再试");
        }
    }
}
